package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.Goods;
import entity.OneCart;
import entity.Order;
import entity.OrderItem;
import entity.UserAddress;
import service.GoodsService;
import service.OrderItemService;
import service.UserAddressService;
import service.UserService;

/**
 * Servlet implementation class CartServlet
 */
@WebServlet("*.cart")
public class CartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	GoodsService goodsService = new GoodsService();

       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String uri = request.getRequestURI();
		int index = uri.lastIndexOf("/");
		String action = uri.substring(index+1);
		switch(action) {
		case "add.cart":
			addCart(request,response);
			break;
		case "in.cart":
			inCart(request,response);
			break;
		case "finished.cart":
			finishedCart(request,response);
			break;
		case "change.cart":
			changeCart(request,response);
			break;
		case "remove.cart":
			removeCart(request,response);
			break;
		default:
			break;
		}
	}

	//添加进购物车
	protected void addCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int confirm = 0;   //用来识别命令
		int goodId = Integer.parseInt(request.getParameter("goodId"));
		int goodNumber = Integer.parseInt(request.getParameter("goodNumber"));
		
		if(request.getSession().getAttribute("cart")==null) {  //如果为空表示第一次购物
			Goods goods = goodsService.getGoodHaveImgByGid(goodId);
			OneCart oneCart = new OneCart(goods, goodNumber);
			List<OneCart> cart = new ArrayList<>();
			cart.add(oneCart);
			request.getSession().setAttribute("cart", cart);
			confirm = 1;
		} else {  //表示已有购物车
			List<OneCart> cart = (List<OneCart>) request.getSession().getAttribute("cart");
			for (OneCart oc : cart) {
				if(oc.getGoods().getGoodId() == goodId) {
					confirm = 2;
				}
			}
			if(confirm != 2) {  //表示购物车里面没有此商品
				Goods goods = goodsService.getGoodHaveImgByGid(goodId);
				OneCart oneCart = new OneCart(goods, goodNumber);
				cart.add(oneCart);
				confirm = 1;
			}
		}
		if(confirm == 1) {
			response.getWriter().write("success");
		} else if(confirm == 2){
			response.getWriter().write("exist");
		}
	}

	//进入购物车
	protected void inCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<OneCart> cart = null;
		int userId = Integer.parseInt((String) request.getSession().getAttribute("loginUserId"));
		if(request.getSession().getAttribute("cart") != null) {  //如果不为空表示购物车有内容
			cart = (List<OneCart>) request.getSession().getAttribute("cart");
		}
		UserService userService = new UserService();
		String passwrod = userService.getPassByUserId(userId);
		UserAddressService userAddressService = new UserAddressService();
		List<UserAddress> addressList = userAddressService.getUserAllAddrByUserId(userId);
		request.setAttribute("pass", passwrod);
		request.setAttribute("addressList", addressList);
		request.setAttribute("cart", cart);
		request.getRequestDispatcher("goodsCart.jsp").forward(request, response);
	}
	
	//完成订单
	protected void finishedCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int userId = Integer.parseInt((String) request.getSession().getAttribute("loginUserId"));
		int addressId = Integer.parseInt(request.getParameter("addressId"));
		List<OneCart> cart = (List<OneCart>) request.getSession().getAttribute("cart");
		List<OrderItem> itemList = new ArrayList<>();
		
		UserAddress userAddress = new UserAddress(addressId);
		Order order = new Order(userId, userAddress, new Date());
		
		for (OneCart one : cart) {
			Goods goods = new Goods(one.getGoods().getGoodId());
			OrderItem orderItem = new OrderItem(goods, one.getGoodNumber(), one.getGoodNumber()*one.getGoods().getGoodPrice());
			itemList.add(orderItem);
		}
		
		OrderItemService orderItemService = new OrderItemService();
		orderItemService.addOrderItem(itemList, order);
		
		request.getSession().removeAttribute("cart");
		request.getRequestDispatcher("search.goods?likeword=").forward(request, response);
	}
	
	//改变数量
	protected void changeCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int changeNumber = Integer.parseInt(request.getParameter("changeNumber"));
		int goodId = Integer.parseInt(request.getParameter("goodId"));
		List<OneCart> cart = (List<OneCart>) request.getSession().getAttribute("cart");
		for (OneCart one : cart) {
			if(one.getGoods().getGoodId() == goodId ) {
				if(changeNumber > 0) {
					one.setGoodNumber(one.getGoodNumber()+changeNumber);
					break;
				} else {
					if(one.getGoodNumber()>1) {
						one.setGoodNumber(one.getGoodNumber()+changeNumber);
						break;
					}
				}
			}
		}
		request.getSession().setAttribute("cart", cart);
		
	}
	
	//去除某件商品
	protected void removeCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int goodId = Integer.parseInt(request.getParameter("goodId"));
		List<OneCart> cart = (List<OneCart>) request.getSession().getAttribute("cart");
		for(int i=0; i<cart.size(); i++) {
			if(cart.get(i).getGoods().getGoodId() == goodId ) {
				cart.remove(i);
				break;
			}
		}
		request.getSession().setAttribute("cart", cart);
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
